<template>
	<view class="navigation">
		<view class="top-view">
			<eui-nav-bar ref="BcmNavBar" title="订单配送" :storeName="sUserStoreName" :storeId="sUserStore"
				:option="nbOption" @menuFunc="onClickMenuFunc" @onClickStore="clickStore" color="#333"
				backgroundColor="white" @onClickRefresh="onClickRefresh">
				<template #storeExtend>
					<view style="flex: 1;font-size:0.75rem;padding-left: 20rpx;" class="text-ellipsis text-center"
						@click="showUserMerchantModal" v-if="sUserMerchantCode">[{{
						sUserMerchantCode }}]{{ sUserMerchantName }} ></view>
				</template>
			</eui-nav-bar>
			<view class="container">
				<scroll-view class="scroll-view" scroll-x scroll-with-animation scroll-animation-duration="240">
					<view :class="activeKey.value == item.value ? 'item on' : 'item'"
						v-for="(item, index) in statusList" :key="index" @click="changeTab(item.value)">
						<view class="name" style="font-size: 32rpx;">{{ item.text }}</view>
						<view class="border"
							:style="{ 'background': activeKey.value == item.value ? 'linear-gradient(159deg, #4FE0EA 0%, #85B6FD 100%)' : '#fff' }">
						</view>
						<view class="number" v-if="item.number > 0 && item.number < 100">{{ item.number }}</view>
						<view class="number" v-if="item.number >= 100">99+</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="main-view" :style="{ height: listHeight + 'rpx' }">
			<eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true"
				:origList="orderList" type="list" :showHeard="false">
				<template v-slot:list="scope">
					<order-item :scope="scope" :chnlTypeList="chnlTypeList" :currentTime="currentTime"></order-item>
				</template>
				<template v-slot:bottom="scope">
					<view>
						<eui-button :modelValue="scope" title="抢单" type="max"
							v-if="scope.orderStatus == '3' && !scope.shipperUserNo" @buttonClick="buttonClick"
							single-tag="confrim"></eui-button>
						<eui-button :modelValue="scope" title="确认取货" type="max" single-tag="picking"
							v-if="scope.orderStatus == '3' && scope.shipperUserNo && scope.deliveryStatus == '9'"
							@buttonClick="buttonClick"></eui-button>
						<eui-button :modelValue="scope" title="确认送达" type="max" single-tag="submit"
							v-if="scope.shipperUserNo && scope.deliveryStatus == '10'"
							@buttonClick="buttonClick"></eui-button>
					</view>
				</template>
			</eui-virtual-list>
		</view>
	</view>
</template>
<script setup type="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import { init, onClickRefresh } from '../../../hooks/bcmInit';
import Enjoy from "../../../common/enjoy"
import OrderItem from './components/OrderItem.vue'
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const bcmUrl = getBcmUrl();

const listHeight = ref(300);  //列表高度
const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const sUserMerchantCode = ref('');
const sUserMerchantName = ref('');
const topHeight = ref(uni.getSystemInfoSync().statusBarHeight + 180)

const CurrentPage = ref(1); //第几页
const PageSize = ref(10); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const orderList = ref([])

const nbOption = ref({
	items: [
		// {title: '我要收货', onClick: 'onClickNewCount', icon: 'plusempty'},
	]
})

const onClickMenuFunc = (e) => {
	console.log('=====onClickMenuFunc: ', e);
	switch (e) {
		case 'onClickNewCount':
			//   setTimeout(() => {
			//     BcmNavBar.value.closeDrawer();
			//   },1200);
			//   uni.navigateTo({
			//     url: './edit?storeId=' + sUserStore.value
			//   });
			break;
	}
}

const statusList = ref([{
	text: '待配送',
	value: '0',
	number: 0
}, {
	text: '待取货',
	value: '1',
	number: 0
}, {
	text: '配送中',
	value: '2',
	number: 0
}])

const formData = ref({
	status: '0',
})
const activeKey = ref({
	value: '0',
})

const timer = ref(null)
const chnlTypeList = ref([])
const currentTime = ref(null)

const startTimer = () => {
	stopTimer();
	timer.value = setInterval(() => {
		currentTime.value = new Date().getTime();
	}, 1000);
}

const stopTimer = () => {
	// 停止定时器
	clearInterval(timer.value);
	timer.value = null;
}

const changeTab = async (value) => {
	activeKey.value = { value }
	formData.value.status = value;
	orderList.value = [];
	fetchOrderData();
	staOrderStatus();
}

const setDefault = async () => {
	sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName : loginInfo.sUserStoreName;
	sUser.value = loginInfo.sUser;
	sUserMerchantCode.value = loginInfo?.merchantCode ? loginInfo?.merchantCode : loginInfo.sDefaultMerchantCode;
	sUserMerchantName.value = loginInfo?.merchantName ? loginInfo?.merchantName : loginInfo.sDefaultMerchantName;
}

const showUserMerchantModal = () => {
	uni.navigateTo({
		url: '/pages/BcmViews/modals/merchant/index'
	})
}

// 选择框点击事件
const clickStore = () => {
	let parms = Enjoy.GetDialogParms();
	parms.CallBack = SelectionChanged;
	parms.SelectionType = "机构选择";
	parms.SelectedItems = sUserStore.value;
	Enjoy.OpenDialog(parms)
}

const SelectionChanged = (event) => {
	if (event.SelectionType == '机构选择') {
		// 更新机构信息
		sUserStoreName.value = event.BackParms.Value;
		sUserStore.value = event.BackParms.Key;
		mainStore.switchStore(event.BackParms.Type, sUserStore.value, sUserStoreName.value);
		uni.$emit(BcmEventType.SWITCH_STORE,{msg:'切换门店'})
			// 按新条件获取数据
			fetchOrderData();
			staOrderStatus();
	} else if (event.type == 'userMerchant') {
		if (event.merchantInfo) {
			mainStore.setUserCurMerchantInfo(event.merchantInfo);
			uni.$emit(BcmEventType.SWITCH_MERCHANT, { msg: '切换商户' });
			sUserMerchantCode.value = event.merchantInfo.merchantCode;
			sUserMerchantName.value = event.merchantInfo.merchantName;
			// 按新条件获取数据
			fetchOrderData();
			staOrderStatus();
		}
	}
}
// 列表下拉刷新
const listPullDown = (e) => {
	fetchOrderData();
	staOrderStatus();
}
// 列表上拉加载
const listPullUp = (e) => {
	if (CurrentPage.value < PageCount.value) {
		CurrentPage.value = CurrentPage.value + 1;
		fetchOrderData(true);
	}
}
const buttonClick = (e) => {
	let { singleTag, modelValue } = e;
	switch (singleTag) {
		case 'confrim':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'orderDeliveryReceiveOrder'
			}, modelValue, undefined, '抢单成功！')
			break;
		case 'picking':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'orderDeliveryConfirmPickup'
			}, modelValue, undefined, '取货成功！')
			break;
		case 'submit':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'orderDeliveryConfirmDelivery'
			}, modelValue, undefined, '送达成功！')
			break;
	}
}

const orderAction = async ({
	uniqueKey,
	methodName
}, v, params = undefined, text = '', fn = undefined) => {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		BillId: v.orderId,
		...params,
	}
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
	await staOrderStatus();
	await fetchOrderData();
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none',
			duration: 2000
		});
	}
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

const fetchOrderData = async (e = undefined) => {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
	}
	const param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		Tag: {
			storeCode: sUserStore.value,
			status: formData.value.status,
			merchantCode: sUserMerchantCode.value
		}
	}
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'orderDeliveryQuery', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	PageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		// console.log(response,'response.ReturnObjectresponse.ReturnObject')
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}

const staOrderStatus = async () => {
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'statisticsByOrderDeliveryStatus', { storeCode: sUserStore.value, merchantCode: sUserMerchantCode.value  });
	response.map(v => {
		statusList.value.map(a => {
			if (a.value == v.status) {
				a.number = v.num
			}
		})
	})
}

const initDict = () => {
	chnlTypeList.value = getBcmDictList('chnlType')
}

onLoad(async () => {
	startTimer()
	await init();
	initDict()
	if (!loginInfo.sUserStore) {
		BcmNavBar.value.onClickStore();
		return;
	}
	setDefault()
	await staOrderStatus();
	await fetchOrderData();
})

onUnmounted(() => {
	stopTimer()
})

defineExpose({
	SelectionChanged
})
</script>
<style lang="scss" scoped>
@import "../../../main.scss";
@import "../common/common.css";
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  background: #FFFFFF;
}
.main-view {
  flex: 1;
  flex-direction: column;
}
::v-deep .list_cell {
	padding-bottom: 14rpx;
  margin: 20rpx 20rpx 0;
}

.content {
	display: flex;
	box-sizing: border-box;
	overflow-x: hidden;
	width: 100%;
	height: 100%;
	padding: 0;
}

.on {
	color: rgba(2, 183, 230, 1);
	font-weight: bold;
}

.border {
	position: absolute;
	bottom: 0;
	left: 105rpx;
	width: 36rpx;
	height: 14rpx;
	border-bottom: none;
}

.content-img {
	position: relative;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: stretch;
	flex: 1;
	box-sizing: border-box;
	background-repeat: no-repeat;

	//background: $uni-background-img;
	background-size: 100% 150px;
}

.navigation {
	flex: 0 0 auto;
}

.m-list-template-list {
	.m-list-top {
		display: "block";
	}
}

.footer {
	flex: 1;
	box-sizing: border-box;
	padding: 0;
	margin: 0;
}

.bottom {
	display: flex;
	justify-content: space-between;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
}

.bottom-1 {
	display: flex;
	justify-content: center;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
	// border-top: 1rpx solid #979797;
}

.popup-content {
	display: flex;
	flex-direction: column;
	width: 100%;
	padding: 0;
	background-color: #fff;

	.popup-title {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		width: 100%;
		height: 100rpx;
		padding-right: 36rpx;
		padding-left: 30rpx;
		font-size: 33rpx;
		line-height: 100rpx;
		border-bottom: 1px solid #f1f1f1;
	}

	textarea {
		box-sizing: border-box;
		width: 100%;
		height: 80px;
		padding: 5px;
		margin: 5px 0;
		border: 1px solid #ccc;
		border-radius: 5px;
	}
}

.container {
	box-sizing: border-box;
	width: 100%;
	height: 80rpx;
	color: #000;
	font-size: 14px;
	background-color: #fff;
	border-bottom: 2rpx solid #fff;
}

.scroll-view {
	display: flex;
	justify-content: space-around;
	align-items: center;
	box-sizing: border-box;
	overflow-x: auto;
	width: 100%;
	height: 100%;
	white-space: nowrap;
}

.item {
	position: relative;
	display: inline-block;
	box-sizing: border-box;
	width: 250rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	text-align: center;
}

.number {
	position: absolute;
	top: 0;
	right: 10rpx;
	height: 30rpx;
	padding: 2px 6px;
	color: #fff;
	font-size: 12px;
	line-height: 30rpx;
	background-color: #f00;
	border-radius: 10px;
}
</style>
